package com.zhj.test.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author zhj
 */
public class NIOServer {
    public static void main(String[] args) throws IOException {
        // 1. 创建 ServerSocketChannel --> ServerSocket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 2. 创建 Selector
        Selector selector = Selector.open();
        // 3. 设置服务端端口
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        // 4. 设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        // 5. 将 serverSocketChannel 注册到 selector 设置监听事件为 OP_ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("key 的数量 " + selector.keys().size());

        while (true) {
            // 1s 没有事件发生
            if (selector.select(3000) == 0) {
                System.out.println("服务器等待3s了，将结束等待！");
                continue;
            }
            // 如果返回>0,就获取到相关的selectKey集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            // 通过selectionKeys可以反向获取集合 事件集合
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                // 事件驱动
                if (key.isAcceptable()) {
                    System.out.println("有新的客户端连接");
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    // 设置为非阻塞
                    socketChannel.configureBlocking(false);
                    // 注册selector 关联Buffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                    System.out.println("生成非阻塞socketChannel:" + socketChannel.hashCode());
                    System.out.println("key 的数量 " + selector.keys().size());
                }
                if (key.isReadable()) {
                    // 通过key反向获取对应channel
                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    // 获取到该channel 关联的 Buffer
                    ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
                    socketChannel.read(byteBuffer);
                    System.out.println("客户端：" + new String(byteBuffer.array()));
                }
                // 手动从集合移出当前key 防止多线程发生重复读取
                iterator.remove();
            }
        }
    }
}
